package com.example.nettyexp.nioc2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.example.nettyexp.c1.ByteBufferUtil.debugRead;

/**
 * @Description : 非阻塞nio
 * @Author : ZYX
 * @Date : 2022/9/9 13:51
 * @Version : 1.0
 **/
@Slf4j
public class AsyncServer {

    public static void main(String[] args) throws IOException {
        // 使用nio来理解阻塞模式
        ByteBuffer buffer = ByteBuffer.allocate(16);

        // 1。创建了服务
        ServerSocketChannel open = ServerSocketChannel.open();
        open.configureBlocking(false);

        // 2。绑定监听端口
        open.bind(new InetSocketAddress(8080));

        // 3. 连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true){
            log.debug("connecting.......");
            // 4.accept 建立与客户端连接
            // socketChannel 用来与客户端之间通信

            // 非阻塞 线程还会继续进行 如果没有连接socketChannel是null
            SocketChannel socketChannel = open.accept();
            if (socketChannel != null){
                log.debug("connected.....{}",socketChannel);
                socketChannel.configureBlocking(false);
                channels.add(socketChannel);
            }


            // 5.接收客户端发送的数据
            for (SocketChannel channel : channels) {
                log.debug("before read...{}",channel);
                int read = channel.read(buffer);
                if (read > 0){
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read----,{}",channel);
                }

            }
        }



    }

}
